<?php

namespace App\Admin\Controllers;

use App\Admin\Components\HouseDashboard;
use App\Admin\Components\HouseNewDevices;
use App\Admin\Components\HouseProductOrders;
use App\Admin\Components\HouseSessions;
use App\Admin\Components\HouseTickets;
use App\Admin\Components\HouseTotalUsers;
use App\Admin\Metrics\Examples;
use App\Http\Controllers\Controller;
use App\Models\Building;
use App\Models\House;
use App\Models\HouseFeeConfig;
use App\Models\Owner;
use App\Models\OwnerItem;
use App\Models\Room;
use Carbon\Carbon;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        return $content
            ->header('租赁系统')
            ->description('数据统计')
            ->body(
                function (Row $row) {
                    $row->column(
                        6,
                        function (Column $column) {
                            $column->row(HouseDashboard::title());
                            $column->row(new HouseTickets());
                        }
                    );

                    $row->column(
                        6,
                        function (Column $column) {
                            $column->row(
                                function (Row $row) {
                                    $row->column(6, new HouseTotalUsers());
                                    $row->column(6, new HouseNewDevices());
                                }
                            );

                            $column->row(new HouseSessions());
                            $column->row(new HouseProductOrders());
                        }
                    );
                }
            );
    }

    /**
     * 新数据统计界面
     * @param Content $content
     * @return Content
     */
    public function index2(Content $content)
    {
        $houses = House::all();
        // 以楼栋为单位获取所有数据
        $buildings = Building::query()->with(
            [
                'rooms',
                'house',
            ]
        )->paginate(1);

        // 整理需要的数据
        $buildings->getCollection()->transform(
            function ($building) {
                foreach ($building->rooms as $room) {
                    // 查询合同情况
                    $owner = Owner::query()->where('ownerable_id', $room->id)
                        ->where('ownerable_type', Room::class)
                        ->first();
                    if (empty($owner)) {
                        continue;
                    }
                    $room->owner = $owner;

                    // 获取租期
                    $room->lease_term = $owner->started_at->toDateString()." ~ ".$owner->ended_at->toDateString();
                    $room->rent = $owner->cycle_price." / ".$owner->cycle.Owner::$cycleUnitMap[$owner->cycle_unit];


                    // 查询当前的未支付项目
                    $ownerItem = OwnerItem::query()->where('owner_id', $owner->id)
                        ->where('count', $owner->now_cycle)
                        ->first();

                    // 合同交租
                    if ($ownerItem->pay_at) {
                        $building->overdue_time = "已支付";
                    } else {
                        $ended_at = Carbon::parse($owner->ended_at);
                        $days = ($ended_at->timestamp - Carbon::now()->timestamp) / (60 * 60 * 24);
                        if ($days > 0) {
                            $room->overdue_time = "<span style='color: forestgreen; font-size: 14px;'> （离最晚交租："
                                . ceil($days) . "天）</span>";
                        } else {
                            $room->overdue_time = "<span style='color: red; font-size: 14px;'> （逾期：" . ceil($days) . "天）</span>";
                        }
                    }

                    // 计算合同在第几期
                    $room->now_cycle = $owner->now_cycle;
                    $room->total_cycle = OwnerItem::query()->count();
                }

                return $building;
            }
        );

        return $content->header('栋楼数据')
            ->description('统计')
            ->body(view('admin.home.index2', compact('buildings', 'houses')));
    }


    public function index3(Content $content)
    {
        // 获取所有数据
        $ownerItems = OwnerItem::query()
            ->with(['owner'])
            ->where('started_at', "<", Carbon::now())
            ->where('started_at', ">", Carbon::now()->subMonths(1))
            ->get()->each(function ($value) {
                $value->nextRentDays = $this->getNextRentDays($value->owner);
            });

        return $content->header('月度数据')
            ->description('统计')
            ->body(view('admin.home.index3', compact('ownerItems')));
    }


    /**
     * 获取距离下次交租的日期
     * @param $owner
     * @return false|float
     */
    private function getNextRentDays($owner)
    {
        if (isset($owner->firstNotPayItem)) {
            $ended_at = \Illuminate\Support\Carbon::parse($owner->firstNotPayItem->ended_at);
            $days = ($ended_at->timestamp - Carbon::now()->timestamp) / (60 * 60 * 24);
        } else {
            $ended_at = Carbon::parse($owner->ended_at);
            $days = ($ended_at->timestamp - Carbon::now()->timestamp) / (60 * 60 * 24);
        }
        
        return $days;
    }

}
